package com.socket.controller;

import com.socket.utils.DateUitl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

@RestController
@RequestMapping("/timer")
public class TimerController {
    private Timer timer;

    @Autowired
    private SimpMessagingTemplate template;

    @GetMapping("/start")
    public String start() {
        timer = new Timer(true);//是否是守护线程 isDaemon为true代表是，否代表不是
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                template.convertAndSend("/topic/sub/red", DateUitl.getDataStr() + "：向/sub/red 发送一次消息");
                template.convertAndSend("/topic/sub/blue", DateUitl.getDataStr() + "：向/sub/blue 发送一次消息");
            }
        }, new Date(), 1000);
        return "启动成功";
    }

    @GetMapping("/stop")
    public String stop() {
        timer.cancel();
        return "关闭成功";
    }
}
